{% extends "base.html" %}

{% block title %}用户注册 - 学术研究自动化平台{% endblock %}

{% block content %}
<div class="row justify-content-center">
    <div class="col-md-8 col-lg-6">
        <div class="card shadow">
            <div class="card-body p-5">
                <div class="text-center mb-4">
                    <i class="fas fa-user-plus fa-3x text-primary mb-3"></i>
                    <h2 class="card-title">用户注册</h2>
                    <p class="text-muted">创建您的研究账户</p>
                </div>
                
                <form id="registerForm" method="POST">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="username" class="form-label">用户名 *</label>
                                <div class="input-group">
                                    <span class="input-group-text">
                                        <i class="fas fa-user"></i>
                                    </span>
                                    <input type="text" class="form-control" id="username" name="username" 
                                           required placeholder="3-50个字符">
                                </div>
                                <div class="form-text">只能包含字母、数字和下划线</div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="email" class="form-label">邮箱地址 *</label>
                                <div class="input-group">
                                    <span class="input-group-text">
                                        <i class="fas fa-envelope"></i>
                                    </span>
                                    <input type="email" class="form-control" id="email" name="email" 
                                           required placeholder="your@email.com">
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="password" class="form-label">密码 *</label>
                                <div class="input-group">
                                    <span class="input-group-text">
                                        <i class="fas fa-lock"></i>
                                    </span>
                                    <input type="password" class="form-control" id="password" name="password" 
                                           required placeholder="至少8个字符">
                                    <button class="btn btn-outline-secondary" type="button" id="togglePassword">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </div>
                                <div class="password-strength mt-2">
                                    <div class="progress" style="height: 5px;">
                                        <div class="progress-bar" id="passwordStrength" role="progressbar" style="width: 0%"></div>
                                    </div>
                                    <small class="form-text" id="passwordHelp">密码强度：弱</small>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="confirmPassword" class="form-label">确认密码 *</label>
                                <div class="input-group">
                                    <span class="input-group-text">
                                        <i class="fas fa-lock"></i>
                                    </span>
                                    <input type="password" class="form-control" id="confirmPassword" name="confirmPassword" 
                                           required placeholder="再次输入密码">
                                </div>
                                <div class="form-text" id="passwordMatch"></div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="role" class="form-label">用户角色</label>
                        <select class="form-select" id="role" name="role">
                            <option value="student">学生</option>
                            <option value="researcher">研究员</option>
                            <option value="guest">访客</option>
                        </select>
                        <div class="form-text">管理员角色需要特殊申请</div>
                    </div>
                    
                    <div class="mb-3 form-check">
                        <input type="checkbox" class="form-check-input" id="agreeTerms" name="agreeTerms" required>
                        <label class="form-check-label" for="agreeTerms">
                            我同意 <a href="#" class="text-decoration-none">服务条款</a> 和 
                            <a href="#" class="text-decoration-none">隐私政策</a>
                        </label>
                    </div>
                    
                    <div class="mb-3 form-check">
                        <input type="checkbox" class="form-check-input" id="newsletter" name="newsletter">
                        <label class="form-check-label" for="newsletter">
                            订阅平台更新通知
                        </label>
                    </div>
                    
                    <div class="d-grid">
                        <button type="submit" class="btn btn-primary btn-lg" id="registerBtn" disabled>
                            <i class="fas fa-user-plus me-2"></i>
                            <span class="btn-text">创建账户</span>
                        </button>
                    </div>
                </form>
                
                <div class="text-center mt-4">
                    <p class="mb-0">
                        已有账户？
                        <a href="{{ url_for('login') }}" class="text-decoration-none">立即登录</a>
                    </p>
                </div>
            </div>
        </div>
        
        <!-- 密码要求说明 -->
        <div class="card mt-3">
            <div class="card-body">
                <h6 class="card-title">
                    <i class="fas fa-info-circle text-info me-2"></i>
                    密码要求
                </h6>
                <ul class="list-unstyled mb-0 small">
                    <li id="length-check"><i class="fas fa-times text-danger me-2"></i>至少8个字符</li>
                    <li id="lowercase-check"><i class="fas fa-times text-danger me-2"></i>包含小写字母</li>
                    <li id="uppercase-check"><i class="fas fa-times text-danger me-2"></i>包含大写字母</li>
                    <li id="number-check"><i class="fas fa-times text-danger me-2"></i>包含数字</li>
                    <li id="special-check"><i class="fas fa-times text-danger me-2"></i>包含特殊字符</li>
                </ul>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
$(document).ready(function() {
    let passwordValid = false;
    let passwordMatch = false;
    
    // 密码显示/隐藏切换
    $('#togglePassword').click(function() {
        const passwordField = $('#password');
        const icon = $(this).find('i');
        
        if (passwordField.attr('type') === 'password') {
            passwordField.attr('type', 'text');
            icon.removeClass('fa-eye').addClass('fa-eye-slash');
        } else {
            passwordField.attr('type', 'password');
            icon.removeClass('fa-eye-slash').addClass('fa-eye');
        }
    });
    
    // 密码强度检查
    $('#password').on('input', function() {
        const password = $(this).val();
        const strength = checkPasswordStrength(password);
        
        updatePasswordStrength(strength);
        checkPasswordMatch();
        updateSubmitButton();
    });
    
    // 确认密码检查
    $('#confirmPassword').on('input', function() {
        checkPasswordMatch();
        updateSubmitButton();
    });
    
    // 其他字段验证
    $('#username, #email, #agreeTerms').on('input change', function() {
        updateSubmitButton();
    });
    
    function checkPasswordStrength(password) {
        let score = 0;
        const checks = {
            length: password.length >= 8,
            lowercase: /[a-z]/.test(password),
            uppercase: /[A-Z]/.test(password),
            number: /\d/.test(password),
            special: /[!@#$%^&*(),.?":{}|<>]/.test(password)
        };
        
        // 更新检查列表
        Object.keys(checks).forEach(check => {
            const element = $(`#${check}-check i`);
            if (checks[check]) {
                element.removeClass('fa-times text-danger').addClass('fa-check text-success');
                score++;
            } else {
                element.removeClass('fa-check text-success').addClass('fa-times text-danger');
            }
        });
        
        passwordValid = score === 5;
        return score;
    }
    
    function updatePasswordStrength(score) {
        const progressBar = $('#passwordStrength');
        const helpText = $('#passwordHelp');
        
        let width, className, text;
        
        if (score === 0) {
            width = 0;
            className = '';
            text = '密码强度：弱';
        } else if (score <= 2) {
            width = 20;
            className = 'bg-danger';
            text = '密码强度：弱';
        } else if (score <= 3) {
            width = 50;
            className = 'bg-warning';
            text = '密码强度：中等';
        } else if (score <= 4) {
            width = 80;
            className = 'bg-info';
            text = '密码强度：良好';
        } else {
            width = 100;
            className = 'bg-success';
            text = '密码强度：强';
        }
        
        progressBar.css('width', width + '%').attr('class', 'progress-bar ' + className);
        helpText.text(text);
    }
    
    function checkPasswordMatch() {
        const password = $('#password').val();
        const confirmPassword = $('#confirmPassword').val();
        const matchText = $('#passwordMatch');
        
        if (confirmPassword === '') {
            matchText.text('');
            passwordMatch = false;
        } else if (password === confirmPassword) {
            matchText.html('<i class="fas fa-check text-success me-1"></i>密码匹配').removeClass('text-danger').addClass('text-success');
            passwordMatch = true;
        } else {
            matchText.html('<i class="fas fa-times text-danger me-1"></i>密码不匹配').removeClass('text-success').addClass('text-danger');
            passwordMatch = false;
        }
    }
    
    function updateSubmitButton() {
        const username = $('#username').val().trim();
        const email = $('#email').val().trim();
        const agreeTerms = $('#agreeTerms').is(':checked');
        
        const isValid = username && email && passwordValid && passwordMatch && agreeTerms;
        $('#registerBtn').prop('disabled', !isValid);
    }
    
    // 表单提交处理
    $('#registerForm').submit(function(e) {
        e.preventDefault();
        
        const $form = $(this);
        const $btn = $('#registerBtn');
        const $btnText = $('.btn-text');
        
        // 禁用按钮并显示加载状态
        $btn.prop('disabled', true);
        $btnText.html('<i class="fas fa-spinner fa-spin me-2"></i>创建中...');
        
        // 获取表单数据
        const formData = {
            username: $('#username').val().trim(),
            email: $('#email').val().trim(),
            password: $('#password').val(),
            role: $('#role').val()
        };
        
        // 发送AJAX请求
        $.ajax({
            url: $form.attr('action') || '{{ url_for("register") }}',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(response) {
                if (response.success) {
                    showAlert('注册成功！正在跳转到登录页面...', 'success');
                    
                    setTimeout(function() {
                        window.location.href = response.redirect || '{{ url_for("login") }}';
                    }, 2000);
                } else {
                    showAlert(response.error || '注册失败', 'danger');
                    resetButton();
                }
            },
            error: function(xhr) {
                let errorMsg = '注册失败，请稍后重试';
                
                if (xhr.responseJSON && xhr.responseJSON.error) {
                    errorMsg = xhr.responseJSON.error;
                }
                
                showAlert(errorMsg, 'danger');
                resetButton();
            }
        });
        
        function resetButton() {
            $btn.prop('disabled', false);
            $btnText.html('<i class="fas fa-user-plus me-2"></i>创建账户');
            updateSubmitButton();
        }
    });
    
    // 显示警告消息
    function showAlert(message, type) {
        const alertHtml = `
            <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        
        $('.alert').remove();
        $('.card-body').prepend(alertHtml);
    }
});
</script>
{% endblock %}